#include "stack.h"

void STInit(ST* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->top = ps->capacity = 0;
}

void STDestroy(ST* ps)
{
	if(ps->arr)
		free(ps->arr);
	ps->arr = NULL;
	ps->top = ps->capacity = 0;
}

bool STEmpty(ST* ps)
{
	assert(ps);

	return ps->top == 0;
}

void STPush(ST* ps, STDataType x)
{
	assert(ps);

	if (ps->top == ps->capacity)
	{
		int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		STDataType* newnode = (STDataType*)realloc(ps->arr, newCapacity*sizeof(STDataType));
		if (newnode == NULL)
		{
			perror("realloc fail");
			exit(1);
		}

		ps->arr = newnode;
		ps->capacity = newCapacity;
	}

	ps->arr[ps->top] = x;
	ps->top++;

}

void STPop(ST* ps)
{
	assert(!STEmpty(ps));

	ps->top--;
}


STDataType STTop(ST* ps)
{
	assert(!STEmpty(ps));

	return ps->arr[ps->top - 1];
}


int STSize(ST* ps)
{
	assert(!STEmpty(ps));
	return ps->top;
}